// main.js
const studentApp = createApp({
    data() {
        return {
            activeView: 'courses', // 默认显示课程列表
            loading: false, // 若为真时，显示加载中
            error: '',
            resp: '', // 响应成功提示
            oldPassword: '',
            newPassword: '',
            selectedSchedule:'', // 选中的课程安排

            // 数据
            teacher:[], // 教师信息
            schedules: [], // 该教师课程安排
            statistics : [], // 班级成绩统计信息
            classAverage: null,
            classMaxScore: null,
        }
    },
    methods: {
        // 登出
        async logout() {
            alert('确定要退出吗')
            window.location.href = window.contextPath+'/api/logout';
        },
        // 加载教师信息
        async loadTeacher(userNo) {
            this.loading = true;
            try {
                const response = await fetch(window.contextPath+'/teacher/get?userNo=' + userNo);
                if (response.ok) {
                    this.teacher = await response.json();
                } else {
                    const errorText = await response.text();
                    this.error = '加载教师信息数据失败'
                    await this.showError()
                }
            } catch (error) {
                this.error = '网络错误: ' + error.message;
                await this.showError()
            } finally {
                this.loading = false;
            }
        },
        // 加载教师课程信息
        async loadSchedules(userNo) {
            this.loading = true;
            try {
                const response = await fetch(window.contextPath+'/schedule/listByTeacherUserNo?userNo=' + userNo);
                if (response.ok) {
                    this.schedules = await response.json();
                } else {
                    const errorText = await response.text();
                    this.error = '加载教师课程数据失败或教师暂无课程数据'
                    await this.showError()
                }
            } catch (error) {
                this.error = '网络错误: ' + error.message;
                await this.showError()
            } finally {
                this.loading = false;
            }
        },
        // 加载班级成绩统计信息
        async loadStatistics(scheduleId) {
            this.loading = true;

            // 课程安排为空时直接返回
            if (!scheduleId) {
                this.statistics = [];
                this.classAverage = null;
                this.classMaxScore = null;
                this.loading = false;
                return;
            }

            try {
                const response = await fetch(window.contextPath+'/grade/listByScheduleId?scheduleId=' + scheduleId);
                if (response.ok) {
                    this.statistics = await response.json();
                    // 获取班级平均分
                    this.classAverage = this.statistics
                        .filter(item => item.score !== undefined && item.score !== null && item.score !== '')
                        .reduce((sum, item) => sum + parseFloat(item.score), 0) /
                        this.statistics.filter(item => item.score !== undefined && item.score !== null && item.score !== '').length;

                    // 获取班级最高分
                    const validScores = this.statistics
                        .filter(item => item.score !== undefined && item.score !== null && item.score !== '')
                        .map(item => parseFloat(item.score));
                    this.classMaxScore = validScores.length > 0 ? Math.max(...validScores) : null;


                } else {
                    const errorText = await response.text();
                    this.error = '加载班级成绩统计数据失败'
                    await this.showError()
                }
            } catch (error) {
                this.error = '网络错误: ' + error.message;
            } finally {
                this.loading = false;
            }
        },
        async saveGrade(statistics) {
            if (!confirm('确定要保存吗，此操作会覆盖原有数据？')) {
                return;
            }
            this.loading = true;
            // 只留下需要的数据
            const data = statistics.map(item => ({
                id: item.gradeId,
                studentUserNo: item.studentNo,
                courseId: item.courseId,
                teacherUserNo: item.teacherUserNo,
                semester: item.semester,
                score: item.score,
                examDate: item.examDate
            }))
            try {
                const response = await fetch(window.contextPath+'/grade/addGrades', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                if (response.ok) {
                    this.resp = '保存成功'
                    await this.showTips()
                    await this.loadStatistics(this.selectedSchedule)
                } else {
                    const errorText = await response.text();
                    this.error = '保存失败:'+errorText
                    await this.showError()
                }
            }catch ( error) {
                this.error = '网络错误: ' + error.message;
                await this.showError()
            } finally {
                this.loading = false;
            }
        },
        async changePassword() {
            if (!confirm('确定要修改密码吗？')) {
                return;
            }

            this.loading = true;
            try {
                const response = await fetch(window.contextPath+'/api/changePassword', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        oldPassword: this.oldPassword,
                        newPassword: this.newPassword,
                        userNo: window.userNo
                    })
                })
                if (response.ok) {
                    this.resp = '修改密码成功'
                    await this.showTips()
                    this.oldPassword = ''
                    this.newPassword = ''
                    alert('密码修改成功，请重新登录')
                    window.location.href = window.contextPath+'/api/logout'
                } else {
                    const errorText = await response.text();
                    this.error = '修改密码失败:' + errorText;
                    await this.showError()
                }
            }catch ( error) {
                this.error = '网络错误: ' + error.message;
                await this.showError()
            }finally {
                this.loading = false;
            }
        },
        showError() {
            // 显示几秒后关闭模态框
            setTimeout(() => {
                this.error = '';
            }, 3000)
        },
        showTips() {
            // 显示几秒后关闭模态框
            setTimeout(() => {
                this.resp = '';
            }, 3000)
        }

    },
    mounted() {
        window.teacherAppInstance = this;
        this.loadTeacher(window.userNo).then(r => console.log('加载教师信息成功'))
        this.loadSchedules(window.userNo).then(r => console.log('加载教师课程信息成功'))
    },

});
studentApp.mount('#teacher-app');

